//
//  WBRefreshControl.swift
//  Weibo
//
//  Created by 冯童童 on 16/1/22.
//  Copyright © 2016年 冯童童. All rights reserved.
//

import UIKit
import SnapKit

enum WBRefreshStatue : Int {
    
    case Normal = 1
    case Pulling = 2
    case Refreshing = 3
}

private let RefreshHeight : CGFloat = 60
class WBRefreshControl: UIControl {

    var oldStatue : WBRefreshStatue = .Normal
    var statue : WBRefreshStatue = .Normal {
        didSet {
            switch statue {
            case .Normal: tipLabel.text = "下拉起飞"
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.arrowIcon.transform = CGAffineTransformIdentity
            })
              arrowIcon.hidden = false
                indicationView.stopAnimating()
            if oldStatue == .Refreshing {
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var inset = self.scrollView!.contentInset
                    inset.top -= RefreshHeight
                    self.scrollView?.contentInset = inset

                })
               
            }

            case .Pulling: tipLabel.text = "准备起飞"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case.Refreshing: tipLabel.text = "正在起飞"
                arrowIcon.hidden = true
                indicationView.startAnimating()
                sendActionsForControlEvents(.ValueChanged)
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                
                var inset = self.scrollView!.contentInset
                inset.top += RefreshHeight
                self.scrollView?.contentInset = inset

            })
                            }
            oldStatue = statue
        }
        
    }
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -RefreshHeight, width: KWidth, height: RefreshHeight)
        
        super.init(frame: rect)
        backgroundColor = UIColor.yellowColor()
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        print(change)
        
        let conaditionValue  = -(self.scrollView?.contentInset.top ?? 0 + RefreshHeight)
        let offsetY = self.scrollView?.contentOffset.y ?? 0
        
        if scrollView!.dragging {
            
            if statue == .Normal && conaditionValue > offsetY  {
                statue = .Pulling
            }else if statue == .Pulling && conaditionValue < offsetY {
                statue = .Normal
            }
        }else {
            if statue == .Pulling{
                statue = .Refreshing
            }
        }
        
    }
    
    func endRefreshing() {
        let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.3))
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
             self.statue = .Normal
        }
      
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        if let myFather = newSuperview as? UIScrollView {
            print("是scrollView")
            scrollView = myFather
             scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    
    deinit{
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    private var scrollView : UIScrollView?
    private func setupUI() {
        addSubview(tipLabel)
        addSubview(arrowIcon)
        addSubview(indicationView)
        
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(tipLabel.snp_left).offset(5)
            make.centerY.equalTo(tipLabel.snp_centerY)
        }
        
        indicationView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon.snp_center)
        }
         
    }
    
    private lazy var tipLabel : UILabel = UILabel(title: "下拉刷新", fontSize: 14, color: UIColor.blueColor())
    private lazy var arrowIcon : UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var indicationView : UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
}
